//
//  CustomTabBar.m
//  NotepadApp
//
//  Created by yobet on 2018/4/12.
//  Copyright © 2018年 HJ. All rights reserved.
//

#import "CustomTabBar.h"

@implementation CustomTabBar


-(instancetype)initWithFrame:(CGRect)frame {
    if (self= [super initWithFrame:frame]) {
        self.frame = frame;
    }
    return self;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *normalImage = [UIImage imageNamed:@"加号"];
        _addBtn.frame = CGRectMake(0, 0, normalImage.size.width, normalImage.size.height);
        [_addBtn setImage:normalImage forState:UIControlStateNormal];
        //去除选择时高亮
        _addBtn.adjustsImageWhenHighlighted = NO;
        _addBtn.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - normalImage.size.width)/2.0,0, normalImage.size.width, normalImage.size.height);
        [_addBtn sizeToFit];
        [self addSubview:_addBtn];
    }
    return _addBtn;

}


- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;

    CGFloat btnx = 0;
    CGFloat btny = 0;
    //5.0是tabbar中的控件的数量
    CGFloat width = w/3.0;
    CGFloat height = h;

    int i=0;
    for (UIView *btn in self.subviews) {
        //判断是否是系统自带的UITabBarButton类型的控件
        if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (i==1) {
                i=2;
            }
            btnx = i*width;
            btn.frame = CGRectMake(btnx, btny, width, height);

            i++;
        }

    }

    //设置自定义button的位置
    self.addBtn.center = CGPointMake(w*0.5, h*0.5);
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
    if (self.isHidden == NO) {
        //将当前tabbar的触摸点转换坐标系，转换到发布按钮的身上，生成一个新的点
        CGPoint newP = [self convertPoint:point toView:self.addBtn];
        
        //判断如果这个新的点是在发布按钮身上，那么处理点击事件最合适的view就是发布按钮
        if ( [self.addBtn pointInside:newP withEvent:event]) {
            return self.addBtn;
        }else{//如果点不在发布按钮身上，直接让系统处理就可以了
            return [super hitTest:point withEvent:event];
        }
    }
    else {//tabbar隐藏了，那么说明已经push到其他的页面了，这个时候还是让系统去判断最合适的view处理就好了
        return [super hitTest:point withEvent:event];
    }
}

@end
